<?php
namespace Modules\Order\Traits;

use ThrowException;
use Setting;
use Cache;

trait Skuable 
{
    // 关联商品
    public function product()
    {
        return $this->belongsTo('\Modules\Product\Entities\Product');
    }

    //  优惠券
    public function coupon()
    {
        return $this->belongsTo('\Modules\Coupon\Entities\Coupon');
    }

    // 按sku类型筛选: custom自定义(无绑定)  product绑定商品  virtual_asset绑定虚拟资产
    public function scopeSkuType($query, $skuType)
    {
        $map = [
            'custom' => 1,
            'product' => 2,
            'virtual_asset' => 3
        ];

        return $query->where('sku_type', @$map[$skuType]);
    }

    // sku type
    public function getSkuTypeTextAttribute()
    {
        $map = [
            1 => 'custom',
            2 => 'product',
            3 => 'virtual_asset',
            4 => 'none'
        ];

        return @$map[$this->sku_type];
    }

    // 是否可以购买
    public function checkCanBuy($user, $total)
    {
        $this->isStockEnough($total) || ThrowException::Conflict('库存不足~');
        $this->isPurchaseTotalLimited($total) && ThrowException::Conflict('每人限购' . $this->limit_total_per_user . '件哦~');

        return true;
    }

    // 是否限制购买数量
    public function isPurchaseTotalLimited($total)
    {
        return ($this->limit_total_per_user && $total > $this->limit_total_per_user);
    }

    // 库存是否足够
    public function isStockEnough($total)
    {
    	return $this->stock >= $total;
    }

    // 是否需要地址
    public function isNeedAddress()
    {
        return $this->parent_product && $this->parent_product->is_need_address;
    }

    // 是否特殊款
    public function isSpecialSku()
    {
        return false;
    }

    // 是否显示库存
    public function isShowStockOnList()
    {
        $setting = $this->getSetting('base');

        if ($this->isSpecialSku()) {
            return @$setting['is_show_stock_special'];
        }
        else {
            return @$setting['is_show_stock_normal'];
        }
    }

    // 是否显示抽中概率 
    public function isShowOddsOnList()
    {
        $setting = $this->getSetting('base');

        if ($this->isSpecialSku()) {
            return @$setting['is_show_odds_special'];
        }
        else {
            return @$setting['is_show_odds_normal'];
        }
    }

    // 增加销量，同时减少库存
    // $isReduceStock 为false时不用扣除库存
    public function addSales($total, $isReduceStock = true)
    {
        // 是否需要扣除库存
        if ($isReduceStock) {
            if ($total > $this->stock) {
                // $this->releaseDB();
                return false;
            }

            $stock = $this->stock - $total;

            $this->stock = $stock < 0 ? 0 : $stock;
        }

        $this->sales = $this->sales + $total;
        $this->save();

        $this->updateSalesSync();

        return true;
    }

    // 撤回销量、同时加回库存
    public function reduceSales($total)
    {
        $sales = $this->sales - $total;

        $this->stock = $this->stock + $total;
        $this->sales = $sales < 0 ? 0 : $sales;
        $this->save();
        
        $this->updateSalesSync();
    }

    // 更新销量的回调 （在具体类中实现）
    public function updateSalesSync()
    {
    }

    // 获得供应商
    public function getSupplier()
    {
        return $this->supplier;
    }

    public function getAttrs()
    {
        return $this->attrs ?: [];
    }

    // 下单资产
    public function getOrderAssets()
    {
        return $this->assets;
    }

    // 获取下单奖励
    public function getRewardAssets($total)
    {
        $rewardAssets = $this->reward_assets;

        if ($rewardAssets === NULL && $this->parent_product) {
            $rewardAssets = $this->parent_product->reward_assets;
        }

        return $rewardAssets;

        // if ($reward)
        //     return $reward * $total;

        return NULL;
    }

    // 获取佣金奖励
    public function getBrokerage($type, $total)
    {
        $field = 'brokerage_' . $type;

        $reward = $this->$field;

        if ($reward === NULL && $this->parent_product) {
            $reward = $this->parent_product->$field;
        }

        if ($reward)
            return $reward * $total;

        return NULL;
    }

    // 获取原价
    public function getOriginalPrice($type = 'money')
    {
        if ($type == 'money') {
            return $this->money_price;
        }
        elseif ($type == 'score') {
            return $this->score_price;
        }
    }

    public function getDiscountPrice($type = 'money', $options = [])
    {
        return $this->getSellingPrice($type, $options);
    }

    public function getSellingPrice($type = 'money', $options = [])
    {
        $activity = @$options['activity'];  // 活动价
        $groupPrice = @$options['group_price'];  // 人群价

        // 检测活动是否有效
        if ($activity && !$activity->isIncludeNode($this)) {
            $activity = NULL;
        }

        // 检测人群价是否有效
        if ($groupPrice && !$groupPrice->isUsableForSku($this)) {
            $groupPrice = NULL;
        }


        // 如果有活动，需要计算活动价
        if ($activity) {
            if ($type === 'money') {
                return $activity->discount_money_price;
            }
            elseif ($type === 'score') {
                return $activity->discount_score_price;
            }        
        }

        // 人群专享价
        if (@$groupPrice) {
            
            if ($type === 'money') {
                return $groupPrice->money_price;
            }
            elseif ($type === 'score') {
                return $groupPrice->score_price;
            } 
        }

        if ($type == 'money') {
            return $this->discount_money_price ?: $this->money_price;
        }
        elseif ($type == 'score') {
            return $this->discount_score_price ?: $this->score_price;
        }
    }

    // 计算多买优惠
    public function calcMultiBuyDiscount($total)
    {
        // 默认
        $moneyDiscount = 0;
        $scoreDiscount = 0;

        // 如果有设置多买优惠
        if ($this->multi_buy_discount && is_array($this->multi_buy_discount)) {
            foreach ($this->multi_buy_discount as $value) {
                if (intVal(@$value['total']) == $total) {
                    // 命中多买优惠的件数设置
                    $moneyDiscount = @$value['discount_money'] ?: 0;
                    $scoreDiscount = @$value['discount_score'] ?: 0;
                    break;
                }
            }
        }

        return [
            $moneyDiscount,
            $scoreDiscount
        ];
    }

    public function isOnlineSku()
    {
        $map = [
            'score',
            'money',
            'coupon',
            'chip',
            'redpack'
        ];
        return in_array($this->type, $map);
    }

    // 发放奖品给用户
    public function sendOnlineAssetToUser($user, $total = 1)
    {
        // 判断绑定虚拟资产类型
        if ($this->type === 'coupon') {
            // 优惠券
            if (!$this->coupon->pushTo($user, 'system', false)) {
                return false;
            }
        }
        elseif ($this->type === 'score') {
            // 积分
            $user->asset('score')->in($this->score * $total, [
                'description' => '活动奖品-' . $this->title
            ]);
        }
        elseif ($this->type === 'redpack') {
            // 绑定发放红包
            $user->asset('redpack')->in($this->redpack * $total, [
                'description' => '活动奖品-' . $this->title
            ]);
        }
        elseif ($this->type === 'custom') {
            // 实物暂不发放
        }

        return true;
    }
}